import 'dart:io';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';
import 'package:archive/archive.dart';
import 'package:shared_preferences/shared_preferences.dart';

/// 文件列表（相对 assets/plugins 的路径）
const pluginFiles = [
  'r_screen_shot.zip',
];

Future<void> copyAndUnzipPlugins() async {
  final dir = await getApplicationSupportDirectory();
  final baseFolder = Directory('${dir.path}/plugins');
  if (!baseFolder.existsSync()) baseFolder.createSync(recursive: true);

  for (final relativePath in pluginFiles) {
    final data = await rootBundle.load('assets/plugins/$relativePath');
    final bytes = data.buffer.asUint8List();

    final zipFile = File('${baseFolder.path}/$relativePath');
    if (!zipFile.parent.existsSync()) zipFile.parent.createSync(recursive: true);
    await zipFile.writeAsBytes(bytes, flush: true);

    // 判断是否是 zip 文件
    if (zipFile.path.endsWith('.zip')) {
      final bytes = await zipFile.readAsBytes();
      final archive = ZipDecoder().decodeBytes(bytes);

      for (final file in archive) {
        final outPath = '${baseFolder.path}/${file.name}';

        if (file.isFile) {
          final outFile = File(outPath);
          if (!outFile.parent.existsSync()) {
            outFile.parent.createSync(recursive: true); // 确保目录存在
          }
          await outFile.writeAsBytes(file.content as List<int>, flush: true);
        } else {
          // 文件夹
          final dir = Directory(outPath);
          if (!dir.existsSync()) {
            dir.createSync(recursive: true);
          }
        }
      }

      print('解压完成: ${zipFile.path}');
    }
  }
}

Future<void> initializePluginsOnce() async {
  final prefs = await SharedPreferences.getInstance();
  final isInitialized = prefs.getBool('plugins_initialized_001') ?? false;
  if (isInitialized) return;

  // 调用复制解压逻辑
  await copyAndUnzipPlugins();

  // 设置标记
  await prefs.setBool('plugins_initialized_001', true);
}
